package org.batch.config.batch.item.reader.csv.line.mapper;

import org.batch.utils.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.file.LineMapper;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.file.transform.LineTokenizer;

/**
 * 统一CSV文件数据读取LineMapper对象
 *
 * @author LiKun
 * @date 2021/9/29 16:10
 */
public class CsvLineMapper<T> implements LineMapper<T> {
    private static final Logger logger = LoggerFactory.getLogger(CsvLineMapper.class);

    private LineTokenizer lineTokenizer;
    private FieldSetMapper<T> fieldSetMapper;

    public CsvLineMapper(Class<T> tClass) {
        logger.info("开始加载CSV文件数据读取器");
        this.lineTokenizer = getLineTokenizer(tClass);
        fieldSetMapper = this.getFieldSetMapper(tClass);
        logger.info("成功加载CSV文件数据读取器");
    }

    @Override
    public T mapLine(String str, int index) throws Exception {
        return this.fieldSetMapper.mapFieldSet(this.lineTokenizer.tokenize(str));
    }

    private FieldSetMapper<T> getFieldSetMapper(Class<T> tClass) {
        return new BeanWrapperFieldSetMapper<T>() {{
            setTargetType(tClass);
        }};
    }

    private LineTokenizer getLineTokenizer(Class<T> tClass) {
        return new DelimitedLineTokenizer() {{
            setNames(ObjectUtil.fieldsWithSuper(tClass));
        }};
    }
}
